import React, { FC } from "react";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import { Datedirection } from "@ct0/icons";
import { TimePicker } from "./Picker";
import { DateType } from "../type";
import { prefixCls } from "../constant";
import DateInput from "./DateInput";

dayjs.extend(customParseFormat);

interface Props {
  selectedDate: [DateType, DateType];
  handleSelectedDate: (value: [DateType, DateType]) => void;
  disabledTime?: boolean;
  startDatePlaceholder?: string;
  endDatePlaceholder?: string;
  startTimePlaceholder?: string;
  endTimePlaceholder?: string;
  isChinese?: boolean;
}

const TimeValues: FC<Props> = ({
  selectedDate,
  handleSelectedDate,
  disabledTime,
  startDatePlaceholder = "开始日期",
  endDatePlaceholder = "结束日期",
  startTimePlaceholder = "开始时间",
  endTimePlaceholder = "结束时间",
  isChinese,
}) => {
  const [startDate, endDate] = selectedDate;
  const handleChange = (action: "start" | "end", time: DateType | null) => {
    let nextValue: [DateType, DateType] = [startDate, endDate];
    if (action === "start") {
      nextValue[0] = time;
    }
    if (action === "end") {
      nextValue[1] = time;
    }
    if (nextValue[0]?.isAfter(nextValue[1])) {
      handleSelectedDate([nextValue[1], nextValue[0]]);
    } else {
      handleSelectedDate(nextValue);
    }
  };
  return (
    <div className={`${prefixCls}-values`}>
      <DateInput
        placeholder={startDatePlaceholder}
        value={startDate}
        onChange={(v: DateType) => {
          handleChange("start", v);
        }}
      />
      {!disabledTime && (
        <div className={`${prefixCls}-values-timePicker`}>
          <TimePicker
            value={startDate}
            onChange={(time: DateType) => {
              handleChange("start", time);
            }}
            placeholder={startTimePlaceholder}
            isChinese={isChinese}
          />
        </div>
      )}
      <Datedirection />
      <DateInput
        placeholder={endDatePlaceholder}
        value={endDate}
        onChange={(v: DateType) => {
          handleChange("end", v);
        }}
      />
      {!disabledTime && (
        <div className={`${prefixCls}-values-timePicker`}>
          <TimePicker
            value={endDate}
            onChange={(time: DateType) => {
              handleChange("end", time);
            }}
            placeholder={endTimePlaceholder}
            isChinese={isChinese}
          />
        </div>
      )}
    </div>
  );
};

export default TimeValues;
